#include "UdpServer.hpp"

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Useage(argv);
        exit(1);
    }

    int _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    std::string ip = argv[1];
    std::string port = argv[2];

    struct sockaddr_in _src;
    memset(&_src, 0, sizeof(_src));
    _src.sin_family = AF_INET;
    _src.sin_addr.s_addr = inet_addr(ip.c_str());
    // _src.sin_port = std::stoi(port);
    _src.sin_port = htons(std::stoi(port)); // 转换成网络序列

    while (1)
    {
        std::string _line;
        std::getline(std::cin, _line);

        socklen_t len = sizeof(_src);
        char buffer[1024] = {0};
        ssize_t n = sendto(_socketfd, _line.c_str(), _line.size(), 0, (struct sockaddr *)&_src, len);
        
        ssize_t m = recvfrom(_socketfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&_src, &len);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}